<!-- 预约管理 -->
<template>
  <div class="main-content-container">
    <!-- 新增预约 -->
    <Dialog
      :title="title"
      :visible.sync="visible"
      :button-text="testBtn"
      :reveal="showBtn"
      :loading="loading"
      @close="handleClose"
      @confirm="submitForm"
    >
      <div v-if="flag">
        <div class="divs">
          <p><span>小明</span><span>135*****0101</span></p>
          <p>此顾客还未预约</p>
          <p>
            <el-button @click="returnBtn">返回</el-button>
            <el-button @click="subscribeBtn">增加预约</el-button>
          </p>
        </div>
      </div>
      <div v-else>
        <el-form
          v-show="!shows"
          ref="subscribeRef"
          :model="addSubscribeForm"
          :rules="subscribeRules"
          label-width="100px"
        >
          <el-form-item label="顾客：" prop="customerName">
            <el-autocomplete
              v-model="addSubscribeForm.customerName"
              :fetch-suggestions="querySearch"
              placeholder="姓名、手机号、编号"
              @select="handleSelect"
            />
          </el-form-item>
          <el-form-item label="预约类型：" prop="appointmentType">
            <dictionary-selector
              code="swan_cutomer_yylx"
              :value.sync="addSubscribeForm.appointmentType"
              @change="handleSelector"
            />
          </el-form-item>
          <el-form-item
            v-if="addSubscribeForm.appointmentType === '治疗/复查'"
            label="项目"
            prop="projectName"
          >
            <el-select
              v-model="addSubscribeForm.projectName"
              placeholder="请选择项目"
              value-key="id"
            >
              <el-option
                v-for="item in projectNameOptions"
                :key="item.id"
                :label="item.projectName"
                :value="item.projectName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="接待人：" prop="receiverName">
            <el-select v-model="addSubscribeForm.receiverName">
              <el-option
                v-for="item in receiverOptions"
                :key="item.id"
                :label="item.usrName"
                :value="item.usrName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间：" prop="appointmentDate">
            <el-col :span="6">
              <el-form-item prop="appointmentDate" class="dateStyle">
                <el-date-picker
                  v-model="addSubscribeForm.appointmentDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择日期"
                  @change="handleDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="appointmentTime" class="dateStyle">
                <el-select
                  v-model="addSubscribeForm.appointmentTime"
                  placeholder="请选择时段"
                  clearable
                >
                  <el-option
                    v-for="item in cities"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value"
                    :disabled="item.label === '不可预约' ? true : false"
                  >
                    <span style="float: left">{{ item.value }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px"
                    >{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="addSubscribeForm.appointmentType === '现场咨询'"
            label="咨询分类："
            prop="advisoryClassification"
          >
            <el-cascader
              v-model="addSubscribeForm.advisoryClassification"
              :options="consultingOptions"
              :props="optionsProps"
            />
          </el-form-item>
          <el-form-item label="预约备注：" prop="appointmentRemark">
            <el-input
              v-model="addSubscribeForm.appointmentRemark"
              type="textarea"
              :autosize="{ minRows: 3 }"
            />
          </el-form-item>
        </el-form>
        <el-form
          v-show="shows"
          ref="lookSubscribeRef"
          :rules="lookSubscribeRules"
          :model="lookSubscribeForm"
          label-width="150px"
        >
          <el-form-item label="顾客：">{{
            lookSubscribeForm.customerName
          }}</el-form-item>
          <el-form-item label="预约类型：">{{
            lookSubscribeForm.appointmentType
          }}</el-form-item>
          <el-form-item label="接待人：">{{
            lookSubscribeForm.receiverName
          }}</el-form-item>
          <el-form-item
            label="预约时间："
          >{{ lookSubscribeForm.appointmentDate }}
            {{ lookSubscribeForm.appointmentTime }}</el-form-item>
          <el-form-item
            v-if="searchForm.appointmentStatus !== '已取消'"
            label="项目分类："
          >{{ lookSubscribeForm.advisoryClassification }}</el-form-item>
          <el-form-item v-if="title !== '取消预约'" label="预约备注：">{{
            lookSubscribeForm.appointmentRemark
          }}</el-form-item>
          <el-form-item
            v-if="title !== '预约签到' && title !== '取消预约'"
            label="预约状态："
          >{{ lookSubscribeForm.appointmentStatus }}
            {{
              lookSubscribeForm.arrivalTime ? lookSubscribeForm.arrivalTime : ""
            }}
          </el-form-item>
          <!-- searchForm.appointmentStatus -->
          <el-form-item
            v-if="searchForm.appointmentStatus === '已取消'"
            label="取消原因："
          >{{ lookSubscribeForm.cancelReason }}</el-form-item>
          <el-form-item
            v-if="searchForm.appointmentStatus === '已取消'"
            label="取消备注："
          >{{ lookSubscribeForm.cancelRemark }}</el-form-item>
          <el-form-item
            v-if="title === '取消预约'"
            label="取消原因："
            :prop="title === '取消预约' ? 'cancelReason' : ''"
          >
            <dictionary-selector
              code="RESERVE_CANCAL_CODE"
              :value.sync="lookSubscribeForm.cancelReason"
              placeholder="取消原因"
            />
          </el-form-item>
          <el-form-item
            v-if="title === '取消预约'"
            label="取消备注："
            prop="cancelRemark"
          >
            <el-input
              v-model="lookSubscribeForm.cancelRemark"
              type="textarea"
              :autosize="{ minRows: 3 }"
            />
          </el-form-item>
        </el-form>
      </div>
    </Dialog>
  </div>
</template>
<script>
// import { getDates } from "@/config";
import Dialog from "@/components/Dialog/index";
export default {
  components: {
    Dialog,
  },
  data() {
    return {
      selections: [
        {
          name: "今天",
          id: "today",
        },
        {
          name: "昨天",
          id: "yesterday",
        },
        {
          name: "近七天",
          id: "week",
        },
        {
          name: "自定义",
          id: "custom",
        },
      ],
      filtrateList: [
        {
          name: "全部",
          id: "全部",
        },
        {
          name: "预约中",
          id: "预约中",
        },
        {
          name: "已到达",
          id: "已到达",
        },
        {
          name: "已过期",
          id: "已过期",
        },
        {
          name: "已取消",
          id: "已取消",
        },
      ],
      searchForm: {
        appointmentStatus: "预约中",
      },
      receiverOptions: [],
      optionsProps: {
        children: "children",
        label: "name",
        value: "name",
        checkStrictly: true, // 选择任意一项
      },
      consultingOptions: [],
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      chargeList: [],
      chargeData: {},
      selectCustomerData: {}, // 新增选中顾客
      addSubscribeForm: {
        appointmentType: "现场咨询",
      },
      lookSubscribeForm: {},
      seleteDate: "", // 预约选择日期
      cities: [], // 预约时段
      restaurants: [], // 顾客数据
      projectNameOptions: [],
      requestInfo: {},
      title: "",
      visible: false,
      testBtn: "",
      showBtn: true,
      loading: false,
      flag: false,
      shows: false,
      showcom: false,
      timer: null, // 定时器
      custQuery: "",
      subscribeRules: {
        customerName: [
          { required: true, message: "请输入顾客名称", trigger: "change" },
        ],
        appointmentType: [
          { required: true, message: "请选择预约类型", trigger: "change" },
        ],
        projectName: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        appointmentDate: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
      },
      lookSubscribeRules: {
        cancelReason: [
          { required: true, message: "请选择取消原因", trigger: "change" },
        ],
      },
    };
  },
  created() {
  },
  // 判断如果定时器还在运行就关闭 或者直接关闭
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    // 增加预约
    subscribeBtn(row) {
      if (row && row.id) {
        this.addSubscribeForm = row;
      }
      this.title = "增加预约";
      this.testBtn = "提交";
      this.shows = false;
      this.flag = false;
      this.showBtn = true;
      this.visible = true;
      this.loadAll();
      this.handleSelector();
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      item.customerId = item.id;
      item.appointmentSource = item.informationSources;
      this.selectCustomerData = item;
      this.getProjectName();
    },
    async loadAll() {
      // 所有顾客详情
      const res = await this.$api["reception/subscribe/findall"]();
      if (res.code === 200) {
        res.data.map((item) => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
      // 咨询分类
      const consultingData = await this.$api[
        "reception/subscribe/consulttype"
      ]();
      if (consultingData.code === 200) {
        this.consultingOptions = consultingData.data.result;
      }
    },
    // 根据职位名称获取所有人员
    async handleSelector(val) {
      // console.log(val); // 1 咨询师 2 主治医生
      if (val === "治疗/复查") {
        val = "主治医生";
      } else {
        val = "咨询师";
      }
      const receiverData = await this.$api[
        "reception/subscribe/getAllByJobName"
      ]({ hospitalJobName: val });
      if (receiverData.code === 200) {
        this.receiverOptions = receiverData.data;
      }
    },
    // 顾客已购项目
    async getProjectName() {
      const res = await this.$api[
        "reception/subscribe/customerIdAllByOrderList"
      ]({ customerId: this.selectCustomerData.id });
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    // 监听选中预约日期变化
    async handleDate() {
      function p(s) {
        return s < 10 ? "0" + s : s;
      }
      const myDate = new Date();
      const year = myDate.getFullYear();
      const month = myDate.getMonth() + 1;
      const day = myDate.getDate();
      const hours = myDate.getHours();
      const minutes = myDate.getMinutes();
      const dates =
        year +
        "-" +
        p(month) +
        "-" +
        p(day) +
        "-" +
        p(hours) +
        "-" +
        p(minutes);
      const currentDate = dates.split("-").join("");
      if (this.addSubscribeForm.appointmentDate) {
        // 预约时段列表
        const timeData = await this.$api["reception/subscribe/getCreateList"]({
          dictionaryId: "785558903319429120",
        });
        if (timeData.code !== 200) return this.$message.error(timeData.message);
        timeData.data.map((item) => {
          item.value = item.name + "-" + item.content;
          const aTime =
            this.addSubscribeForm.appointmentDate + "-" + item.content;
          const bTime = aTime.split(":").join("");
          this.seleteDate = bTime.split("-").join("");
          // console.log(currentDate, '当前本地时间');
          // console.log(this.seleteDate, '选择预约时间');
          if (Number(currentDate) > Number(this.seleteDate)) {
            item.label = "不可预约";
          } else {
            item.label = "可预约";
          }
        });
        this.cities = timeData.data;
      }
    },
    // 返回
    returnBtn() {
      this.visible = false;
      this.flag = false;
      this.searchForm = {};
      this.$emit('handleSuccess');
    },
    judgeConditions() {
      this.flag = false;
      this.shows = true;
      this.showBtn = true;
      this.visible = true;
      this.showcom = false;
    },
    // 查看
    lookBtn(row) {
      this.lookSubscribeForm = row;
      this.title = "查看预约";
      this.testBtn = "确认";
      this.judgeConditions();
    },
    // 签到
    async signInBtn(row) {
      this.title = "预约签到";
      this.testBtn = "签到并分诊";
      this.lookSubscribeForm = row;
      if (row.appointmentType === "治疗/复查") {
        this.lookSubscribeForm.advisoryClassification = row.projectName;
      } else {
        this.lookSubscribeForm.advisoryClassification =
          row.advisoryClassification;
      }

      this.judgeConditions();
    },
    async getUpdateReportData() {
      const res = await this.$api["reception/subscribe/updateReport"]({
        ...this.lookSubscribeForm,
      });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.visible = false;
      this.$emit('handleSuccess');
    },
    // 提交-确认
    submitForm() {
      if (this.title === "增加预约") {
        this.$refs.subscribeRef.validate(async(valid) => {
          if (valid) {
            if (
              this.addSubscribeForm.appointmentTime &&
              this.addSubscribeForm.appointmentDate
            ) {
              if (this.addSubscribeForm.appointmentType === "现场咨询") {
                this.addSubscribeForm.advisoryClassification = this.addSubscribeForm.advisoryClassification[0];
              }
              if (this.selectCustomerData && this.selectCustomerData.sex) {
                this.selectCustomerData.customerSex = this.selectCustomerData.sex;
              }
              const res = await this.$api[
                "reception/subscribe/addappointment"
              ]({ ...this.addSubscribeForm, ...this.selectCustomerData });
              if (res.code !== 200) { return this.$message.error("新增预约失败！"); }
              this.$message.success("新增预约成功！");
              this.visible = false;
              this.$refs.subscribeRef.resetFields();
              this.$emit('handleSuccess');
            } else {
              this.$message.info("必须选择预约时间！");
            }
          }
        });
      } else if (this.title === "预约签到") {
        this.getUpdateReportData();
        this.showcom = true;
        this.$nextTick(() => {
          this.$refs.addSubscribeRef.addTriageBtn(this.lookSubscribeForm);
        });
      } else if (this.title === "取消预约") {
        this.$refs.lookSubscribeRef.validate((valid) => {
          if (valid) {
            this.getUpdateReportData();
            this.$message.success("取消预约成功！");
            this.$refs.lookSubscribeRef.resetFields();
          }
        });
      } else {
        this.visible = false;
      }
    },
    // 关闭
    handleClose() {
      if (this.title === "增加预约") {
        this.$refs.subscribeRef.resetFields();
      } else {
        this.$refs.lookSubscribeRef.resetFields();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.divs {
  text-align: center;
  p {
    margin: 20px 0;
    span {
      margin: 0 15px;
    }
    .el-button {
      margin: 0 45px;
    }
  }
}
.dateStyle {
  margin-bottom: 0;
}
::v-deep .el-autocomplete {
  width: 100%;
}
</style>

